<template>
  <div>
    <el-table-form ref="form" class="form" :model="query">
      <el-form-item :table-form-merge="1.5" class="merge-item">
        <el-select v-model="query.type1" style="width: 200px;">
          <el-option label="客户电话" value="csmPhone" />
          <el-option label="客户名称" value="csmName" />
          <el-option label="申请人" value="userName" />
        </el-select>
        <el-input v-model="query.csmText" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="query.type2" style="width: 50%;">
          <el-option label="欠瓶时间" value="lessTime" />
          <el-option label="实际归还时间" value="backTime" />
        </el-select>
        <el-date-picker
          v-model="query.date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="所属机构:" class="merge-item">
        <el-tree-select
          v-model="query.orgSNNo"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择组织机构',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="状态:" class="merge-item">
        <el-select v-model="query.status">
          <el-option v-for="(l,i) in enumMap" :key="i" :label="l.desc" :value="l.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="" class="merge-item">
        <el-checkbox v-model="query.todo">待处理</el-checkbox>
      </el-form-item>
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button type="primary" icon="el-icon-download" :loading="$loadingPlugin.exportFile" @click="exportFile">导出</el-button>
        <el-button type="primary" icon="el-icon-folder-add" @click="addBottle">新增欠瓶</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{bottomOffset:10}"
      v-loading="$loadingPlugin.fetchData"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <addBottle ref="addBottle" @refresh="refresh" />
    <detailbottle ref="detail" />
  </div>
</template>

<script>
  import { parseTime } from '@/utils'
  // import tableData from './tabelData.json'
  import { oweBottleList, queryMap, oweBottleUpdate, queryExportDomain, oweBottleExport } from '@/api'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'

  export default {
    name: 'rentManage',
    components: {
      addBottle: require('./components/add.vue').default,
      detailbottle: require('./components/details.vue').default
    },
    data() {
      return {
        exportDomain: null, // 导出域名
        query: {
          type1: 'csmPhone',
          type2: 'lessTime',
          date: [new Date((new Date()).getFullYear(), (new Date()).getMonth(), 1), new Date()], // 当前月第一天和当前日  默认值
          status: null,
          checked: false
        },
        treeData: [],
        enumMap: [
          // { 'value': -1, 'desc': '作废', 'key': 'INVALID' },
          // { 'value': 1, 'desc': '未审核', 'key': 'UNCHECK' },
          // { 'value': 2, 'desc': '待归还', 'key': 'CHECKED_TOBE_RETURN' },
          // { 'value': 3, 'desc': '已归还待确认', 'key': 'RETURNED_TOBE_CONFIRM' },
          // { 'value': 4, 'desc': '已归还', 'key': 'RETURNED' },
          // { 'value': 5, 'desc': '作废待确认', 'key': 'INVALID_TOBE_CONFIRM' }
        ],

        tableData: {
          column: [
            {
              prop: 'userName',
              label: '申请人',
              align: 'center',
              width: 100,
              showOverflowTooltip: true
            },
            {
              prop: 'csmCode',
              label: '客户编码',
              align: 'center'

            },
            {
              prop: 'csmName',
              label: '客户名称',
              align: 'center'

            },
            {
              prop: 'csmPhone',
              label: '联系电话',
              align: 'center',
              width: '150'
            },
            {
              prop: 'csmAddress',
              label: '客户地址',
              align: 'center',
              showOverflowTooltip: true,
              width: '200'
            },
            {
              prop: 'gasDesc',
              label: '欠瓶描述',
              align: 'center',
              showOverflowTooltip: true,
              width: '200'
            },
            {
              prop: 'status',
              label: '状态',
              align: 'center',
              width: '120',
              render: (h, { row }) => <span style={this.getColor(row.status)}>{this.enumMap.find(l => row.status === l.value) ? this.enumMap.find(l => row.status === l.value).desc : ''}</span>
            },
            {
              prop: 'startDt',
              label: '欠瓶时间',
              align: 'center',
              width: '200',
              render: (h, { row }) => <span>{ row.startDt && parseTime(row.startDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'planBackDt',
              label: '预计还瓶时间',
              align: 'center',
              width: '200',
              render: (h, { row }) => <span>{ row.planBackDt && parseTime(row.planBackDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'endDt',
              label: '实际归还时间',
              align: 'center',
              width: '200',
              render: (h, { row }) => <span>{ row.endDt && parseTime(row.endDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'recGPBMIDS',
              label: '钢瓶号',
              align: 'center',
              showOverflowTooltip: true,
              width: '150'
            },
            {
              prop: 'recChipIDS',
              label: '芯片号',
              align: 'center',
              showOverflowTooltip: true,
              width: '150'
            },
            {
              prop: 'orgName',
              label: '责任机构',
              align: 'center',
              showOverflowTooltip: true,
              width: '180'
            },
            {
              prop: 'auditor',
              label: '审核人',
              align: 'center',
              width: ''
            },
            {
              prop: 'auditDt',
              label: '审核时间',
              align: 'center',
              width: '200',
              render: (h, { row }) => <span>{ row.auditDt && parseTime(row.auditDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              label: '操作',
              align: 'left',
              fixed: 'right',
              width: 210,
              render: (h, { row, $index }) => {
                return (
                  // <div>
                  //   <el-link size='mini' onClick={() => this.audit(row)}>
                  //   {row.status === 1 ? '审核' : ''}
                  //   </el-link>
                  //    <el-link size='mini' onClick={() => this.affirm(row, $index)}>
                  //     {row.status === 2 || row.status === 3 ? '还瓶确认' : ''}
                  //   </el-link>
                  //   <el-link size='mini' type='danger' onClick={() => this.cancellation(row, $index)}>
                  //   {row.status === 1 ? '作废 ' : ''}
                  //   </el-link>
                  //   <el-link size='mini' type='primary' onClick={() => this.details(row, $index)}>
                  //    欠瓶明细
                  //   </el-link>
                  // </div>
        //             审核 2
        // 作废 -1
        // 还瓶 4
                  <div class='handle'>
                {row.status === 1 && <el-link size='mini' onClick={() => this.handle(row, 2)}> 审核</el-link>}
                {(row.status === 2 || row.status === 3) && <el-link size='mini' onClick={() => this.handle(row, 4)}>还瓶确认 </el-link>}
                { row.status === 1 && <el-link size='mini' type='danger' onClick={() => this.handle(row, -1)}>  作废 </el-link>}
                    <el-link size='mini' onClick={() => this.details(row, $index)}>欠瓶明细 </el-link>
                  </div>
                )
              }
            }

          ],
          data: [{ 'id': 1634181774298, 'goodsName': '退残回收测试', 'goodsId': 946, 'gprince': 200, 'tag': 20000, 'definePrice': 0, 'diff': 0, 'gcount': 1, 'gprefPrice': 0, 'tip': 0, 'fee1': 0, 'fee2': 0, 'baseFloorFee': 0, 'treceivable': '200.00', 'gtId': 48, 'gtFlag': 1, 'priceScore': 0, 'requiredScore': 0, 'pricingMode': 2, 'specCode': 'S0649', 'specName': '5型', 'storeCount': 0, 'isSpeicalPriceFloor': false, 'yf': 0, 'tip1': 0 }, { 'id': 1634181786832, 'goodsName': '15KG液化气', 'goodsId': 761, 'gprince': 0.01, 'tag': 1, 'definePrice': 0, 'diff': 0, 'gcount': 1, 'gprefPrice': 0, 'tip': 0, 'fee1': 0, 'fee2': 0.01, 'baseFloorFee': 0, 'treceivable': '0.02', 'gtId': 48, 'gtFlag': 1, 'priceScore': 0, 'requiredScore': 0, 'pricingMode': 1, 'specCode': 'S0336', 'specName': '15KG', 'storeCount': 0, 'isSpeicalPriceFloor': false, 'yf': '0.00', 'fee21': '0.01', 'tip1': '0.00' }, { 'id': 1634181790522, 'goodsName': '赵越超专用', 'goodsId': 951, 'gprince': 0.01, 'tag': 1, 'definePrice': 0, 'diff': 0, 'gcount': 2, 'gprefPrice': 0, 'tip': 0, 'fee1': 0, 'fee2': 0, 'baseFloorFee': 0, 'treceivable': '0.02', 'gtId': 48, 'gtFlag': 1, 'priceScore': 0, 'requiredScore': 0, 'pricingMode': 1, 'specCode': 'S0336', 'specName': '15KG', 'storeCount': 0, 'isSpeicalPriceFloor': false, 'yf': 0, 'tip1': 0 }, { 'id': 1634184016558, 'goodsName': '15KG液化气（培训）', 'goodsId': 839, 'gprince': 100, 'tag': 10000, 'definePrice': 0, 'diff': 0, 'gcount': 1, 'gprefPrice': 0, 'tip': 0, 'fee1': 11, 'fee2': 3, 'baseFloorFee': 0, 'treceivable': '114.00', 'gtId': 48, 'gtFlag': 1, 'priceScore': 0, 'requiredScore': 0, 'pricingMode': 1, 'specCode': 'S0336', 'specName': '15KG', 'storeCount': 0, 'isSpeicalPriceFloor': false, 'yf': '11.00', 'fee21': '3.00', 'tip1': '0.00' }, { 'id': 1634184026166, 'goodsName': '12KG液化气', 'goodsId': 733, 'gprince': 100, 'tag': 10000, 'definePrice': 0, 'diff': 0, 'gcount': 1, 'gprefPrice': 0, 'tip': 1, 'fee1': 3, 'fee2': 1, 'baseFloorFee': 0, 'treceivable': '105.00', 'gtId': 48, 'gtFlag': 1, 'priceScore': 0, 'requiredScore': 0, 'pricingMode': 1, 'specCode': 'S0488', 'specName': '12KG', 'storeCount': 0, 'isSpeicalPriceFloor': false, 'yf': '3.00', 'fee21': '1.00', 'tip1': '1.00' }]
        }

      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ])
    },
    created() {
      this.getTreeData()
      this.getStatusMap()
    },
    mounted() {
      this.$watch('query.todo', (val) => {
        this.fetchData({})
      })
      // this.tableData.data = tableData.data.rows
      // console.log(tableData)
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.orgSNNo = value.orgSNNo
      },
      search() {
        this.fetchData({})
      },
      // 新增
      addBottle() {
        this.$refs.addBottle.open()
      },
      // // 审核
      // audit(row) {

      // },
      // // 还瓶确认
      // affirm(row) {

      // },
      // // 作废
      // cancellation(row) {

      // },
      // 欠瓶明细
      details(row) {
        this.$refs.detail.open(row)
      },
      async fetchData({ currentPage = 1, pageSize = 20 }) {
        const params = {
          currentPage,
          pageSize,
          orgSNNo: this.query.orgSNNo,
          status: this.query.status,
          todo: Boolean(this.query.todo)
        }
        params[this.query.type1] = this.query.csmText
        // if()
        console.log(this.query.type2)
        if (this.query.date) {
          if (this.query.type2 === 'lessTime') {
            params['startDtStart'] = this.query.date[0]
            params['startDtEnd'] = this.query.date[1]
          } else if (this.query.type2 === 'backTime') {
            params['endDtStart'] = this.query.date[0]
            params['endDtEnd'] = this.query.date[1]
          }
        }
        // startDtStart
        console.log({ ...params })
        // startDtEnd
        const res = await oweBottleList(params)
        if (res.success) {
          this.tableData.data = res.data.rows
        }
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      refresh() {
        this.fetchData({})
      },
      // 操作
      async handle(row, num) {
        // 审核 2
        // 作废 -1
        // 还瓶 4
        if (!num) return
        const params = {
          id: row.id,
          status: num
        }
        console.log(params)
        var txt = ''
        switch (num) {
        case 2:txt = '审核'
               break
        case -1:txt = '作废'
                break
        case 4:txt = '还瓶'
               break
        }
        this.$confirm(`确认${txt}?`, '提示', {
          type: 'warning'
        }).then(async() => {
          const res = await oweBottleUpdate(params)
          if (res.success) {
            this.$message.success('操作成功')
            this.fetchData({})
          }
        })
      },
      getColor(val) {
        var colorObj = {
          1: 'color:#ff0000;',
          2: 'color:#cc33ff;',
          3: 'color:#389E0D;',
          4: 'color:#01999f;',
          5: 'color:#330066;'
        }

        return colorObj[val]
      },
      async getStatusMap() {
        const res = await queryMap({ enumName: 'UserOrgGasRecordStatus' })
        console.log(res)
        this.enumMap = res.data
      },
      // 导出
      async exportFile() {
        // console.log(this.exportDomain)
        // console.log(url)
        this.$confirm('确定要导出吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          await this.getExportDomain()
          var list = JSON.parse(JSON.stringify(this.tableData.column))
          list.pop()
          // console.log(list)
          const value = {}
          list.forEach(l => {
            value[l.prop] = l.label
            return value
          })
          const params = {
            kv: value,
            paramInfo: {
              orgSNNo: this.query.orgSNNo,
              status: this.query.status,
              todo: Boolean(this.query.todo)
            }
          }
          // console.log(params)
          params['paramInfo'][this.query.type1] = this.query.csmText
          await oweBottleExport(params).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        }).catch((e) => {
          console.log(e)
        })
      },
      // 获取导出域名
      async getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
            return res.data
          })
      }

    }
  }
</script>

<style scoped lang="scss">
  .form {
    display: flex;
    flex-wrap: wrap;
    // justify-content: space-between;
    // & /deep/ .el-form-item {
    //   .el-form-item__content > .el-select {
    //     width: 100%;
    //   }
    // }
    // .block {
    //   width: 100%;
    // }
  }
  .handle {
    display: flex;
  }
</style>
